package controllers;

import static play.libs.Json.toJson;
import models.Task;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;



public class Application extends Controller {

    static Form<Task> taskForm = form(Task.class);

    public static Result index() {
        // return ok(index.render("Your new application is ready."));
        return redirect(routes.Application.tasks());
    }

    public static Result tasks() {
        return ok(views.html.index.render(Task.all(), taskForm));
    }

    public static Result newTask() {
        
        // bind da requisicao
        Form<Task> filledForm = taskForm.bindFromRequest();

        if (filledForm.hasErrors())
            return badRequest(views.html.index.render(Task.all(), filledForm));
        
        // recupera o objeto        
        Task task = filledForm.get();
		
        // verifica se é uma edição
        Task oldTask = Task.findById(task.id);
        
        if (oldTask != null) {
            oldTask.label = task.label;
        } else {
            oldTask = task;
        }
        
        Task.create(oldTask);
            
        return ok(toJson(task));
    }

    public static Result deleteTask(Long id) {
        Task.delete(id);
        return redirect(routes.Application.tasks());
    }

}